<template>
    <div class="page_root" :key="queryUpdateFlag" data-page-name="端到端配置" data-page-identification="b_me6r95fb2k">
        <a-spin :spinning="pageLoading.loading" :tip="pageLoading.tip">
            <!-- begin vid_fx4by4f2wk 自定义模板_d6jtujy9x8 -->
            <div class="inner-div">
                <a-tabs v-model:activeKey="state.endToEndRadio" @change="getEndToEnd">
                    <a-tab-pane key="里程碑项目阶段周期" tab="里程碑项目阶段周期" />
                    <a-tab-pane key="项目排序" tab="项目排序" />
                    <a-tab-pane key="延期偏差颜色设置" tab="" force-render />
                </a-tabs>
                <!--                        <a-col :span="10" :offset="7">-->
                <a-form
                    :model="state.milepostList"
                    ref="milepostRef"
                    v-if="state.endToEndRadio === '里程碑项目阶段周期'"
                >
                    <div class="module-item" v-for="(item, index) in state.milepostList" :key="index">
                        <div class="form-content">
                            <a-row>
                                <a-col :span="8">
                                    <a-form-item
                                        :labelCol="{ span: 12 }"
                                        :wrapperCol="{ span: 12 }"
                                        label="里程碑项目阶段名称"
                                        :rules="[
                                            {
                                                required: true,
                                                message: '请输入目里程碑项目阶段名称！',
                                                trigger: 'blur'
                                            }
                                        ]"
                                        :name="[index, 'stageName']"
                                    >
                                        <a-input v-model:value="state.milepostList[index].stageName" />
                                    </a-form-item>
                                </a-col>
                                <a-col :span="8">
                                    <a-form-item
                                        :labelCol="{ span: 6 }"
                                        :wrapperCol="{ span: 18 }"
                                        label="时间周期"
                                        :rules="[{ required: true, message: '请输入时间周期', trigger: 'blur' }]"
                                        :name="[index, 'stagePeriod']"
                                    >
                                        <a-input-number
                                            style="width: 100%"
                                            min="0"
                                            v-model:value="state.milepostList[index].stagePeriod"
                                        />
                                    </a-form-item>
                                </a-col>
                                <a-col :span="8">
                                    <a-form-item
                                        :labelCol="{ span: 6 }"
                                        :wrapperCol="{ span: 18 }"
                                        label="排序"
                                        :rules="[
                                            { required: true, message: '请输入序号', trigger: 'blur' },
                                            {
                                                pattern: new RegExp(/^(0(\.\d{1,2})?|[1-9]\d*(\.\d{1,2})?)$/),
                                                message: '仅支持小数点后两位的正数',
                                                trigger: 'blur'
                                            }
                                        ]"
                                        :name="[index, 'stageNo']"
                                    >
                                        <a-input-number
                                            style="width: 100%"
                                            v-model:value="state.milepostList[index].stageNo"
                                        />
                                    </a-form-item>
                                </a-col>
                            </a-row>
                        </div>

                        <a class="del" @click="handlerDeleteMile(index)">删除</a>
                        <a class="add-btn" @click="handlerAddMile(index, '下方')">下方插入</a>
                    </div>
                </a-form>
                <div style="overflow-y: auto; height: calc(100vh - 300px)" v-if="state.endToEndRadio === '项目排序'">
                    <div class="default-table">
                        <a-table
                            bordered
                            rowKey="taskId"
                            :columns="suceColumns"
                            :data-source="state.projectSchedulingList"
                            :pagination="false"
                            :scroll="{ y: state.tableHeight }"
                            :row-class-name="(_record, index) => (index % 2 === 1 ? 'table-striped' : null)"
                        >
                            <template #bodyCell="{ column, record, index }">
                                <template v-if="column.dataIndex === 'seq'">
                                    <a-input-number
                                        style="width: 100%"
                                        v-model:value="record.seq"
                                        precision="2"
                                        @blur="subSche(index)"
                                    />
                                </template>
                            </template>
                        </a-table>
                    </div>
                </div>
                <!--                        </a-col>-->
                <a-space v-if="state.endToEndRadio === '里程碑项目阶段周期'">
                    <a-button type="primary" ghost @click="handlerAddMile(index, '最后')"
                        ><template #icon><plus-outlined /></template>新增</a-button
                    >
                    <a-button type="primary" @click="submitMile">保存</a-button>
                </a-space>
            </div>
            <!-- end vid_fx4by4f2wk 自定义模板_d6jtujy9x8 -->
        </a-spin>
    </div>
</template>
<script setup lang="tsx">
    import {
        h,
        ref,
        reactive,
        toRaw,
        markRaw,
        watch,
        computed,
        onBeforeMount,
        onMounted,
        onBeforeUnmount,
        onUnmounted,
        onActivated,
        onDeactivated
    } from 'vue'
    import { useRoute, useRouter } from 'vue-router'
    const router = useRouter()
    const route = useRoute()
    import { get, post, put, del, request, requestWithHeaders } from '@/utils/http/Axios'
    import {
        cloneDeep,
        localGet,
        merge,
        getDifferenceArray,
        traversalTreeStructure,
        checkCaseCondition,
        renderStringInTemplate,
        handleBreadcrumbJump,
        throttle,
        permission,
        getComponentParamsValue
    } from '@/utils/index'
    import { isNullOrEmpty, isEmptyArr, isNullOrUnDef, isContained, isArray, isEmpty, isObject } from '@/utils/is'
    import dayjs from 'dayjs'
    import { getPagePcChartsDataSourceConvert } from '@/utils/chart'
    import { message, notification, Modal } from 'ant-design-vue'
    import {
        propertyFormatByNumber,
        propertyFormatByPercentage,
        propertyFormatByDate,
        parseSubFromDataList
    } from '@/utils/format'
    import colorTheme from '@/design/custom-theme.json'
    /*** PUBLISH_EXEGESIS ***
    import UserTableRecords from '@/model/UserTableRecords';
    import { getAppBaseUrl } from '@/utils/index';
    import { sendToken } from "@/hooks/useIframeToken";
    import { useSystemStore } from "@/store/modules/system";
    const systemStore = useSystemStore();
    *** PUBLISH_EXEGESIS ***/

    // 获取传入的流程ID和组件参数
    const props = defineProps({
        'processInstanceId': {
            type: [String, Number, Boolean],
            default: undefined
        },
        'tabName': {
            type: [String],
            default: undefined
        }
    })
    const immediateWatch = (source, callback) => {
        watch(source, callback, { deep: true, immediate: true })
    }

    /* -------------------------- 属性定义 -------------------------- */

    const setTimeOutList = []
    const pageLoading = reactive({
        loading: false,
        tip: undefined
    })
    const authInfo = localGet('app-user-store')

    // 处理校验
    const setSubFormName = (parentInfo, name) => {
        return [parentInfo.parents, parentInfo.cycleIndex, name]
    }

    /* ========================== 属性定义 ========================== */

    /* -------------------------- 元素数据引用 -------------------------- */

    /* ========================== 元素数据引用 ========================== */

    /* -------------------------- 页面数据 -------------------------- */

    /* ========================== 页面数据 ========================== */

    /* -------------------------- 响应 -------------------------- */

    /* ========================== 响应 ========================== */

    /* -------------------------- 函数 -------------------------- */

    /* ========================== 函数 ========================== */

    /* -------------------------- 页面参数 -------------------------- */

    const pageParameter_state = reactive({
        'processInstanceId': props.processInstanceId ?? route.query.processInstanceId
    })

    /* ========================== 页面参数 ========================== */

    /* -------------------------- 组件事件处理方法 -------------------------- */

    // ---------------------------- 组件数据同步 ----------------------------

    // ============================ 组件数据同步 ============================

    /* ========================== 组件事件处理方法 ========================== */

    /* -------------------------- 生命周期 -------------------------- */
    // 用于参数变更后重新执行自定义指令
    const queryUpdateFlag = ref(0)
    onMounted(() => {})

    onUnmounted(() => {
        // 销毁定时器
        setTimeOutList.forEach(({ repeat, timer }) => {
            repeat ? clearInterval(timer) : clearTimeout(timer)
        })
    })

    /* ========================== 生命周期 ========================== */

    /* -------------------------- 数据关联处理 -------------------------- */

    /* -------------------------- 表单数据同步 -------------------------- */
    /* ========================== 表单数据同步 ========================== */

    /* ========================== 数据关联处理 ========================== */

    /* -------------------------- 不同组件自定义的处理逻辑 -------------------------- */

    /* ========================== 不同组件自定义的处理逻辑 ========================== */

    // ================================定制化逻辑========================================
    const useTabName = ref('END_TO_END')
    import { watchEffect } from 'vue'
    const { tabName } = props
    watchEffect(() => {
        if (props.tabName) {
            useTabName.value = props.tabName
            getEndToEnd()
        }
    })
    const state = reactive({
        milepostList: [],
        endToEndRadio: '里程碑项目阶段周期',
        tableHeight: 600,
      projectSchedulingList:[]
    })
    function getEndToEnd() {
        post('/solution-ppm/api/v2/built-in-system-ppm/project_progress_stage_config/search', {
            'orderBy': 'id',
            'conditions': [
                {
                    'field': 'product_line',
                    'value': useTabName.value,
                    'operator': 'EQ',
                    'valueType': 'STRING'
                }
            ]
        }).then(data => {
            state.milepostList = data.data
        })
        getProjectNo()
    }

    // 项目阶段颜色部分
    const mileItem = {
        stageName: undefined,
        stageNo: undefined,
        stagePeriod: undefined
    }
    const colorItem = {
        stageName: undefined,
        stageNo: undefined,
        stagePeriod: undefined
    }
    function handlerAddMile(index, type) {
        if (type === '最后') {
            state.milepostList.push({ ...mileItem, productLine: useTabName.value })
        } else {
            // 否则使用 splice 方法在 index 后插入
            state.milepostList.splice(index + 1, 0, {
                ...mileItem,
                productLine: useTabName.value
            })
        }
    }

    function handlerDeleteMile(index) {
        state.milepostList.splice(index, 1)
    }
    const milepostRef = ref(null)
    function submitMile() {
        milepostRef.value.validate().then(() => {
            put(
                '/solution-ppm/api/v2/built-in-system-ppm/project_progress_stage_config/batch_modify',
                state.milepostList
            ).then(data => {
                if (data.code !== 200) {
                    message.error(data.message)
                    return
                }
                message.success(data.message)
                getEndToEnd()
            })
        })
    }
    const suceColumns = [
        {
            title: '区域',
            dataIndex: 'areaName',
            align: 'center'
        },
        {
            title: '项目',
            dataIndex: 'projectName',
            align: 'center'
        },

        {
            title: '排序',
            dataIndex: 'seq',
            align: 'center'
        }
        // {
        //     title: '优先级',
        //     dataIndex: 'priorityId',
        //     align: 'center'
        // }
    ]
    function getProjectNo() {
        get(
            `/solution-ppm/api/v2/built-in-system-ppm/dashboard_config/project_list?productLine=${useTabName.value}`
        ).then(data => {
            if (data.code !== 200) {
                message.error(data.message)
                return
            }
            state.projectSchedulingList = data.data
        })
    }

    function subSche(index) {
        put(
            '/solution-ppm/api/v2/built-in-system-ppm/dashboard_config/project_config',
            state.projectSchedulingList[index]
        ).then(data => {
            if (data.code !== 200) {
                message.error(data.message)
                return
            }
            message.success(data.message)
            getProjectNo()
        })
    }
    const headerOffset = ref(220)
    const calcTableHeight = () => {
        state.tableHeight = window.innerHeight - 150 - headerOffset.value
    }

    onMounted(() => {
        calcTableHeight()
        window.addEventListener('resize', calcTableHeight)
    })

    onBeforeUnmount(() => {
        window.removeEventListener('resize', calcTableHeight)
    })
</script>
<style lang="less" scoped>
    .page_root {
        width: 100%;
        height: 100%;
        overflow: auto;
    }
    .page_root :deep(.@{ant-prefix}-spin-nested-loading),
    .page_root :deep(.@{ant-prefix}-spin-container) {
        height: 100%;
    }
    .page_root :deep(.@{ant-prefix}-spin-container .@{ant-prefix}-table-wrapper) {
        display: flex;
        flex-flow: column nowrap;
        justify-content: flex-start;
    }
    .page_root :deep(.@{ant-prefix}-table) {
        flex: auto;
        overflow: auto;
    }
    .table-moreBtn_down {
        overflow: hidden;
        white-space: nowrap;
        text-overflow: ellipsis;
        width: 100px;
    }

    .table-moreBtn_menu :deep(.table-moreBtn_menu-item):hover {
        background: #ebf1ff;
    }

    /*  表格树结构样式处理，展开按钮层级增加*/
    :deep(.@{ant-prefix}-table-row-expand-icon) {
        z-index: 1;
    }
    /*  表格树结构 由于每个表格项采用自定义组件，使用绝对定位布局，开启树结构导致显示异常，暂时使用层级定位位置 */
    :deep(.@{ant-prefix}-table-row-level-1 .@{ant-prefix}-table-cell-with-append .cell-wrapper-left) {
        left: 15px !important;
        width: calc(100% - 15px);
    }
    :deep(.@{ant-prefix}-table-row-level-2 .@{ant-prefix}-table-cell-with-append .cell-wrapper-left) {
        left: 30px !important;
        width: calc(100% - 30px);
    }
    :deep(.@{ant-prefix}-table-row-level-3 .@{ant-prefix}-table-cell-with-append .cell-wrapper-left) {
        left: 45px !important;
        width: calc(100% - 45px);
    }
    :deep(.@{ant-prefix}-table-row-level-4 .@{ant-prefix}-table-cell-with-append .cell-wrapper-left) {
        left: 60px !important;
        width: calc(100% - 60px);
    }

    /* 穿梭框改变默认样式，为根据组件样式控制左右栏宽度。 */
    :deep(.@{ant-prefix}-transfer-list) {
        height: 100%;
        width: 50%;
    }
    .inner-div {
        background-color: #fff;
        height: 100%;
    }
    .inner-div :deep(.ant3-tabs-tab) {
        margin-left: 10px;
    }
    .inner-div :deep(.ant3-tabs-tab-btn) {
        text-align: center;
        //width: 68px;
        height: 32px;
        padding: 0 5px;
        line-height: 32px;
    }
    .inner-div :deep(.ant3-tabs-tab-active) {
        //width: 68px;
        height: 32px;
        background: #f0f2f5;
        border-radius: 16px;
        color: #262626;
        line-height: 32px;
        top: 12px;
    }
    .inner-div :deep(.ant3-tabs-ink-bar) {
        display: none !important;
    }
    .inner-div :deep(.ant3-tabs-tab.ant3-tabs-tab-active .ant3-tabs-tab-btn) {
        color: #262626;
        font-weight: 700;
        background: #f0f2f5;
        border-radius: 16px;
    }
    .form-content {
        display: inline-block;
        width: calc(100% - 80px);
    }
    .del {
        width: 28px;
        color: #3875ff;
        position: absolute;
        right: 35px;
        top: 5px;
    }
    .module-item {
        width: 80%;
        position: relative;
    }
    .add-btn {
        position: absolute;
        right: -35px;
        color: #3875ff;
        top: 5px;
    }
</style>
